<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form ref="queryForm" :inline="true" :model="queryParams" size="small">
        <el-form-item prop="params.commodityName">
          <el-input
            v-model="queryParams.params.commodityName"
            class="filter-item"
            clearable
            placeholder="商品名称"
            style="width: 150px;"
          />
        </el-form-item>
        <el-form-item prop="params.tabName">
          <el-select
            v-model="queryParams.params.tabName"
            clearable
            placeholder="分区名称"
            style="width: 100%"
          >
            <el-option
              v-for="item in tabNameList"
              :key="item.id"
              :label="item.value"
              :value="parseInt(item.code)"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="startDate">
          <el-date-picker
            v-model="queryTime"
            end-placeholder="上架结束日期"
            range-separator="至"
            start-placeholder="上架开始日期"
            style="width: 100%"
            type="datetimerange"
            @change="queryTimeChangeHandler"
          />
        </el-form-item>
        <!-- 按钮 -->
        <el-button
          v-permission="['/store/online/search']"
          v-waves
          class="filter-item"
          icon="el-icon-search"
          size="small"
          style="margin-left: 10px;"
          type="primary"
          @click="getDataList"
        >查询
        </el-button>
        <el-button
          v-permission="['/store/online/add']"
          v-waves
          class="filter-item"
          icon="el-icon-plus"
          size="small"
          type="primary"
          @click="handleOpenDialog('add')"
        >新增
        </el-button>
        <el-button
          v-permission="['/store/online/search']"
          v-waves
          class="filter-item"
          icon="el-icon-refresh"
          size="small"
          type="primary"
          @click="resetQueryForm"
        >重置
        </el-button>
      </el-form>
    </div>
    <!-- 数据表格 -->
    <el-table
      v-loading="dataListLoading"
      :data="dataList"
      border
      fit
      highlight-current-row
      size="small"
      style="width: 100%;"
      @sort-change="handleSortChange"
    >
      <el-table-column :index="shownIndex" align="center" fixed label="序号" type="index" />
      <el-table-column align="center" label="商品名称" prop="commodityName" show-overflow-tooltip />
      <el-table-column align="center" label="商品分区" prop="tabShowName" show-overflow-tooltip />
      <el-table-column align="center" label="上架时间" prop="startDate" show-overflow-tooltip />
      <el-table-column align="center" label="下架时间" prop="endDate" show-overflow-tooltip />
      <el-table-column align="center" label="积分兑换" prop="pointExchange" show-overflow-tooltip />
      <el-table-column align="center" label="积分加钱兑换" prop="pointPlusExchange" show-overflow-tooltip />
      <el-table-column align="center" label="积分数量" prop="pointCost" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.pointCost ? scope.row.pointCost : 0 }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="线上数量" prop="onlineNumber" show-overflow-tooltip />
      <el-table-column align="center" label="创建人" prop="creatorName" show-overflow-tooltip />
      <el-table-column align="center" label="创建时间" prop="createdDate" show-overflow-tooltip />
      <el-table-column align="center" label="编辑时间" prop="modifiedDate" show-overflow-tooltip />
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="250">
        <template slot-scope="scope">
          <el-popover placement="bottom" trigger="click" width="320">
            <el-divider>二维码</el-divider>
            <vue-qr :size="300" :text="qrCodeUrl" />
            <el-divider>{{ scope.row.commodityName }}</el-divider>
            <el-button
              slot="reference"
              v-permission="['/store/online/search']"
              v-waves
              size="mini"
              style="margin-right: 10px;"
              type="success"
              @click="showQrcode(scope.row)"
            >二维码
            </el-button>
          </el-popover>
          <el-button
            v-permission="['/store/online/update']"
            v-waves
            size="mini"
            type="primary"
            @click="handleOpenDialog('update', scope.row)"
          >编辑
          </el-button>
          <el-button
            v-permission="['/store/online/delete']"
            v-waves
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        :current-page="queryParams.page"
        :page-size="queryParams.size"
        :page-sizes="[10,20,30, 50]"
        :total="total"
        background
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 新增-编辑对话框 -->
    <el-dialog
      v-loading="dialogLoading"
      :close-on-click-modal="false"
      :title="dialogTitleMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      element-loading-text="保存中"
      width="50%"
    >
      <el-form
        ref="dataForm"
        :model="dataForm"
        :rules="rules"
        label-position="left"
        label-width="150px"
        size="small"
      >
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="商品名称：" label-width="20" prop="commodityId">
              <el-select
                v-model="dataForm.commodityId"
                :disabled="dialogStatus !== 'add'"
                :loading="fuzzyQueryLoading"
                :remote-method="getCommodityListByKeyword"
                clearable
                filterable
                placeholder="名称/条码/自编码"
                remote
                reserve-keyword
                style="width: 100%;"
                @change="handleCommodityChange"
              >
                <el-option v-for="item in commodityList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="商品价格：" label-width="100" prop="salePrice">
              <el-input v-model="dataForm.salePrice" placeholder="商品价格" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="'线上数量：库存数量【'+quantity+'】'" label-width="20" prop="onlineNumber">
              <el-input v-model="dataForm.onlineNumber" placeholder="线上数量" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="分区名称：" label-width="20" prop="tabName">
              <el-select
                v-model="dataForm.tabName"
                clearable
                placeholder="分区名称"
                style="width: 100%"
              >
                <el-option
                  v-for="item in tabNameList"
                  :key="item.id"
                  :label="item.value"
                  :value="parseInt(item.code)"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="上架下架时间：" prop="startDate">
              <el-date-picker
                v-model="dateTime"
                end-placeholder="结束日期"
                range-separator="至"
                start-placeholder="开始日期"
                style="width: 50%"
                type="datetimerange"
                @change="dateChangeHandler"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="积分兑换：" prop="pointExchange">
              <el-select
                v-model="dataForm.pointExchange"
                :disabled="dataForm.pointPlusExchange===0"
                clearable
                placeholder="积分兑换"
                style="width: 100%"
              >
                <el-option
                  v-for="item in determineList"
                  :key="item.id"
                  :label="item.value"
                  :value="parseInt(item.code)"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="积分加钱兑换：" prop="pointPlusExchange">
              <el-select
                v-model="dataForm.pointPlusExchange"
                :disabled="dataForm.pointExchange===0"
                clearable
                placeholder="积分加钱兑换"
                style="width: 100%"
              >
                <el-option
                  v-for="item in determineList"
                  :key="item.id"
                  :label="item.value"
                  :value="parseInt(item.code)"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              v-if="dataForm.pointExchange===0 || dataForm.pointPlusExchange===0"
              label="积分数量："
              prop="pointCost"
            >
              <el-input v-model="dataForm.pointCost" placeholder="积分数量" type="number" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              v-if="dataForm.pointPlusExchange===0"
              label="加钱金额："
              prop="plusMoneyCost"
            >
              <el-input v-model="dataForm.plusMoneyCost" placeholder="加钱金额" type="number" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus==='add'" size="small" type="primary" @click="handleAdd">确定</el-button>
        <el-button v-if="dialogStatus==='update'" size="small" type="primary" @click="handleUpdate">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { add, del, fetchList, update } from '@/api/store/onlineStock'
import { fuzzyQuery } from '@/api/store/commodity'
import { typeList } from '@/api/system/dict'
import moment from 'moment'
import { mapGetters } from 'vuex'
import VueQr from 'vue-qr'

export default {
  name: 'Online',
  components: {
    VueQr
  },
  data() {
    return {
      total: 0,
      dataList: [],
      dateTime: [],
      commodityList: [],
      determineList: [],
      tabNameList: [],
      quantity: 0,
      dataListLoading: true,
      dialogFormVisible: false,
      fuzzyQueryLoading: false,
      dialogLoading: false,
      dialogStatus: '',
      qrCodeUrl: '',
      queryTime: [],
      dialogTitleMap: {
        add: '新增',
        update: '编辑'
      },
      // 查询参数对象
      queryParams: {
        page: 1,
        size: 10,
        params: {
          commodityName: '',
          tabName: '',
          startDate: '',
          endDate: ''
        }
      },
      dataForm: {
        commodityId: '',
        tabName: '',
        startDate: '',
        endDate: '',
        pointExchange: 1,
        pointPlusExchange: 1,
        pointCost: 0,
        onlineNumber: '',
        plusMoneyCost: 0
      },
      rules: {
        commodityId: [{ required: true, message: '商品名称不能为空', trigger: 'change' }],
        onlineNumber: [{ required: true, message: '线上数量不能为空', trigger: 'change' }],
        startDate: [{ required: true, message: '上线时间不能为空', trigger: 'change' }]
      }
    }
  },
  computed: {
    ...mapGetters(['wxServerUrl']),
    formReadOnly() {
      return this.dialogStatus === 'view'
    }
  },
  mounted() {
    this.getDataList()
    typeList({ type: 'determine' }).then(res => {
      this.determineList = res.data
    })
    typeList({ type: 'tabName' }).then(res => {
      this.tabNameList = res.data
    })
  },
  methods: {
    shownIndex(index) {
      return (this.queryParams.page - 1) * this.queryParams.size + index + 1
    },
    handleSortChange(data) {
      console.log('handleSortChange')
      console.log(data)
      if (data.order) {
        if (data.order.indexOf('asc') > -1) {
          this.queryParams.sortOrder = 'asc'
        } else {
          this.queryParams.sortOrder = 'desc'
        }
        this.queryParams.sortName = data.prop
      }
      console.log(this.queryParams)
      this.getDataList()
    },
    // 手动重置表单
    resetDataForm() {
      if (this.$refs['dataForm']) {
        // 由于编辑数据的时候会导致表单对象的初始化值发生变更，所以在重置表单前先手动重置表单对象的值
        this.dataForm = {
          commodityId: '',
          tabName: '',
          startDate: '',
          endDate: '',
          pointExchange: 1,
          pointPlusExchange: 1,
          pointCost: 0,
          onlineNumber: '',
          plusMoneyCost: 0
        }
        this.$refs['dataForm'].resetFields()
      }
    },
    resetQueryForm() {
      this.$refs['queryForm'].resetFields()
      this.queryParams.page = 1
      this.queryTime = []
      this.queryParams.params.startDate = ''
      this.queryParams.params.endDate = ''
      this.getDataList()
    },
    getDataList() {
      this.dataListLoading = true
      fetchList(this.queryParams)
        .then(res => {
          console.log(res)
          this.dataList = res.data.records
          this.total = res.data.total
          this.dataListLoading = false
          this.$message.success(res.msg || '获取数据成功')
        })
        .catch(err => {
          console.log(err)
          this.dataListLoading = false
        })
    },
    handleSizeChange(size) {
      this.queryParams.size = size
      this.getDataList()
    },
    handleCurrentChange(page) {
      this.queryParams.page = page
      this.getDataList()
    },
    async handleOpenDialog(type, rowData) {
      // 表单状态为新增/编辑、打开新增/编辑窗口
      this.resetDataForm()
      this.dialogStatus = type
      this.dialogFormVisible = true
      if (type === 'update') {
        this.getCommodityListByKeyword('All')
        this.dataForm = JSON.parse(JSON.stringify(rowData))
        this.dateTime = [moment(this.dataForm.startDate), moment(this.dataForm.endDate)]
        this.handleCommodityChange(this.dataForm.commodityId)
      }
    },
    handleAdd() {
      // 先进行表单校验
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.dialogLoading = true
          add(this.dataForm)
            .then(res => {
              console.log(res)
              this.$message.success(res.msg || '新增成功')
              this.dialogLoading = false
              this.dialogFormVisible = false
              this.resetDataForm()
              this.getDataList()
            })
            .catch(err => {
              console.log(err)
              this.dialogLoading = false
            })
        }
      })
    },
    handleUpdate() {
      // 先进行表单校验
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.dialogLoading = true
          update(this.dataForm)
            .then(res => {
              console.log(res)
              this.$message.success(res.msg || '修改成功')
              this.dialogLoading = false
              this.dialogFormVisible = false
              this.resetDataForm()
              this.getDataList()
            })
            .catch(err => {
              console.log(err)
              this.dialogLoading = false
            })
        }
      })
    },
    handleDelete(rowData) {
      this.$confirm('是否删除该记录？', '删除提示', { type: 'warning' })
        .then(() => {
          del(rowData.id)
            .then(res => {
              console.log(res)
              // this.$message.success(res.msg || '删除成功')
              this.getDataList()
            })
            .catch(err => {
              console.log(err)
            })
        })
        .catch(cancel => {
          console.log(cancel)
        })
    },
    dateChangeHandler(value) {
      if (value) {
        this.dataForm.startDate = value[0]
        this.dataForm.endDate = value[1]
      }
    },
    // 模糊查询商品列表
    getCommodityListByKeyword(query) {
      console.log('getCommodityListByKeyword')
      console.log(query)
      this.fuzzyQueryLoading = true
      setTimeout(() => {
        fuzzyQuery(query).then(res => {
          console.log(res)
          this.commodityList = res.data
          this.fuzzyQueryLoading = false
        }).catch(err => {
          console.log(err)
          this.fuzzyQueryLoading = false
        })
      }, 200)
    },
    handleCommodityChange(commodityId) {
      console.log(commodityId)
      setTimeout(() => {
        const tmpList = this.commodityList.filter(item => item.id === commodityId)
        if (tmpList.length === 1) {
          this.dataForm.salePrice = tmpList[0].salePrice
          this.quantity = tmpList[0].quantity === null ? 0 : tmpList[0].quantity
        }
      }, 500)
    },
    queryTimeChangeHandler(value) {
      if (value) {
        this.queryParams.params.startDate = value[0]
        this.queryParams.params.endDate = value[1]
      }
    },
    showQrcode(rowData) {
      debugger
      console.log(rowData)
      this.qrCodeUrl = this.wxServerUrl + '/pages/store/mall.html?commodityId=' + rowData.commodityId
    }
  }
}
</script>
<style scoped>

.el-form-item {
  margin-bottom: 30px;
}

</style>
